package main

import (
	"fmt"
	"math"
	"strconv"
)

func decodeString(s string) string {
	var res string
	var stack []string
	for _, b := range s {
		if len(stack) == 0 {
			stack = append(stack, string(b))
			continue
		}
		if b != ']' {
			stack = append(stack, string(b))
			continue
		}
		var tmpStr string
		for len(stack) != 0 {
			top := stack[len(stack)-1]
			stack = stack[0 : len(stack)-1]
			if top == "[" {
				break
			}
			tmpStr = top + tmpStr
		}
		var cnt int
		var pos int
		for len(stack) != 0 {
			cntStr := stack[len(stack)-1]
			c, err := strconv.ParseInt(cntStr, 10, 32)
			if err == nil {
				stack = stack[0 : len(stack)-1]
				cnt += int(math.Pow10(pos)) * int(c)
				pos++
				continue
			}
			break
		}
		if cnt == 0 { // 避免a[c]这种没有数字的情况
			cnt++
		}
		var newStr string
		for i := 0; i < cnt; i++ {
			newStr += tmpStr
		}
		stack = append(stack, newStr)
	}
	for len(stack) != 0 {
		top := stack[len(stack)-1]
		res = top + res
		stack = stack[0 : len(stack)-1]
	}
	return res
}

func main() {
	s := "3[a]2[bc]"
	s = "3[a[c]]"
	s = "3[a2[c]]"
	// s = "2[abc]3[cd]ef"
	// s = "abc3[cd]xyz"
	// s = "100[leetcode]"
	fmt.Println(decodeString(s))
}
